<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.box{
			width: 800px;
			height: 1000px;
			border: 1px red solid;
			margin: 0 auto;
			position: relative;
		}
		.item{width: 200px;position: absolute;background-color: pink;font-size: 50px;text-align: center;color: white;}
	</style>
</head>
<body>
	<div class="box">
	</div>
</body>
<script type="text/javascript">
	var box=document.getElementsByClassName("box")[0];
	var n = 4;//代表几列
	var allHeight = [];//每列总高度
	for (var i = 0; i < n; i++) {
		allHeight[i] = 0;
	}
	var num=0;
	for (var j = 0; j < 20; j++) {
		// 1、生成div
		var newDiv = document.createElement("div");
		// 2、设置样式
		newDiv.className = "item";
		newDiv.style.height = parseInt(Math.random()*150+100) + "px";
		
		num++;
		newDiv.innerText = num;
		box.appendChild(newDiv);
		// 3、找总高度最小列的下标
		var minIndex = 0;
		for (var i = 0; i < n; i++) {
			if (allHeight[minIndex]>allHeight[i]) {
				minIndex=i;
			}
		}
		// 4、根据下标设置left top
		newDiv.style.left = minIndex * (newDiv.offsetWidth ) + "px";
		newDiv.style.top = allHeight[minIndex] + "px";
		
		// 5、div放入最短列之后，最短列总高度增加
		allHeight[minIndex] += (newDiv.offsetHeight+10);
	}
		
</script>
</html>